package server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import exceptions.LogsReceiveException;
import exceptions.LogsStoreException;

public class DMSServerThread implements Runnable{
	Socket s;//该线程服务的客户端对应的socket
	LogWriter writer;//输出登录记录数据的对象
	private List<DMSServerThread> list;
	public DMSServerThread() {
	}
	
	public DMSServerThread(Socket s,List<DMSServerThread> list){
		this.s=s;
		this.list=list;
		list.add(this);
	}
	
	public void run() {
		List<String> list = new ArrayList<String>();
		try {
			String labip=s.getInetAddress().getHostAddress();//也可以让客户端在发数据前发送过来，建立连接时读取的时候先读一次
			list = readLog();
			writer = new DBLogWriter();
			writer.writeLog(labip, list);
			this.list.remove(this);
		} catch (LogsReceiveException e) {
//			e.printStackTrace();
		} catch (LogsStoreException e) {
//			e.printStackTrace();
		}
	}
	
	private List<String> readLog() throws  LogsReceiveException{
		List<String> list = new ArrayList<String>();
		try {
			InputStream in = s.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			OutputStream out = s.getOutputStream();
			PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
			String s;
			while((s=reader.readLine())!=null){
				writer.println("success");
				writer.flush();
//				当未对客户端发送过来的信息作反应，客户端多次发送相同的消息过来，
				//读到的信息可能是完全相同的
				if(!list.contains(s))//转换为MatchedLog对象
					list.add(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new LogsReceiveException(e);
		}
		return list;
	}

}
